# -*- coding: utf-8 -*-
import FPLib
from sqlalchemy import *
from sqlalchemy.orm import session, sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.sql import text

# session_factory = sessionmaker()
# scoped_session_factory = scoped_session(session_factory)

# print(session_factory)

class ORMSession(session.Session):
# class Session(scoped_session_factory):

    def __init__(self, *p, **kw):
        super(ORMSession, self).__init__(*p, **kw)
        self.result = False

    def q(self, sql, *p, **kw):
        self.result = None
        # log.info("execute:",sql)
        self.result = self.execute(text(sql), *p, **kw)
        # print(self.result)
        return self.result

    def _parse_result(self, act="scalar", result=None):
        if result is None:
            result = self.result
        res = None
        if result is not None:
            if hasattr(result, act):
                call = getattr(result, act)
                if callable(call):
                    res = call()
        return res

    def _parse_dict(self, result=None, max_count=0):
        if result is None:
            result = self.result
        res = []
        count = 0
        for v in result:
            line = {}
            for column, value in v.items():
                # print('{0}: {1}'.format(column, value))
                line[column] = value
            res.append(line)
            count += 1
            if max_count and count >= max_count:
                break
        return res

    def count(self, result=None):
        if result is None:
            result = self.result
        res = None
        try:
            res = result.rowcount
        except Exception as e:
            res = None
        return res

    def get(self, result=None):
        return self._parse_result(act="scalar", result=result)

    def getone(self, result=None):
        return self._parse_result(act="fetchone", result=result)

    def getall(self, result=None):
        return self._parse_result(act="fetchall", result=result)

    def one(self, result=None):
        res = {}
        tres = self._parse_dict(result=result, max_count=1)
        if len(tres) > 0:
            res = tres[0]
        return res

    def all(self, result=None):
        return self._parse_dict(result=result)

    def arr(self, result=None):
        return self.all(result=result)

    def end(self):
        self.commit()

    def back(self):
        self.rollback()
